package com.example.video.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.video.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class translateUtil {


    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";
    @Value("${baiduAPPID}")
    private String appid;
    @Value("${baiduKEY}")
    private String securityKey;


   // q是要翻译的文本，from是q使用的语言，to是要翻译的语言
    public Result<String> getTransResult(String q, String from, String to) {
        log.info("translateUtil -> getTransResult ->msg: q = " + q + " from = " + from + " to = " + to);
        // 请求参数
        Map<String, String> params = buildParams(q, from, to);

        Result<String> result = new Result<String>();
        List<String> list = new ArrayList<>();
        if(params == null)
        {
            result.setCode(-1);
            result.setMsg("传入字符串有空值");
            list.add("输入有空值");
            result.setData(String.join("",list));
            result.setCount(0);
//            log.info("translateUtil -> getTransResult ->msg:result ="+result);
            return result;
        }
        // data是返回值String类型
        String data = HttpGet.get(TRANS_API_HOST, params);
//        log.info("translateUtil -> getTransResult ->msg:data = " + data);
        JSONObject dataJson = JSONObject.parseObject(data);
//        log.info("translateUtil -> getTransResult ->msg:dataJson = " + dataJson);
        JSONArray jsonArray = dataJson.getJSONArray("trans_result");

        if(data.contains("error_code"))
        {
            result.setCode(-1);
            result.setMsg("请求出错，返回错误码和错误信息");
//            list.add(jsonArray.getJSONObject(0).getString("dst"));
            result.setData(String.join("\n",list));
            result.setCount(jsonArray.size());
        }
        else{
            if(!jsonArray.isEmpty())
            {
                for(int i = 0; i < jsonArray.size(); i++) {
//                text = transData.get(i).split("}")[0].substring(7, transData.get(i).split("}")[0].length() - 1);
                    list.add(jsonArray.getJSONObject(i).getString("dst"));
                }
                result.setData(String.join("\n",list));
                result.setCount(list.size());
                result.setMsg("OK");
                result.setCode(0);
                log.info("translateUtil -> getTransResult ->msg:翻译结果 ="+result.getData());
            }else{
                log.warn("jsonArray为空，翻译出现问题！"+data);
                result.setData(null);
                result.setCount(0);
                result.setMsg("jsonArray为空，翻译出现问题！"+data);
                result.setCode(-1);
            }
        }
//        log.info(result);
        return result;
    }

    private Map<String, String> buildParams(String q, String from, String to) {

        if(q == null || from == null || to == null)
            return null;

        Map<String, String> params = new HashMap<String, String>();
        params.put("q", q);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", this.appid);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = this.appid + q + salt + this.securityKey; // 加密前的原文
        params.put("sign", MD5Utils.md5(src));

        return params;
    }

}
